package com.rill.action;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.rill.po.User;
import com.rill.service.UserService;

/**
 * 登录
 */
public class LoginAction extends ActionSupport {
	// 登录需要用户名和密码
	private String username;
	private String password;
	private UserService userService;// 登录需要查注册时的用户名和密码

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public String execute() throws Exception {
		// 前端传来的参数传给po
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);

		// 获取request
		HttpServletRequest request = ServletActionContext.getRequest();
		
		if (userService.loginUser(user)) {// 业务操作
			request.setAttribute("url", "user/getBlogInfo.action");
			request.setAttribute("info", "成功");

			/*// 动态获取username：方式一：request.getSession()
			HttpSession session = request.getSession();//把username的放到session中，先通过request获取session
			session.setAttribute("username",username);//添加username变量到session中
*/			
			/*方式二：ActionContext.getContext.getSession()获取session*/
			Map session = ActionContext.getContext().getSession();//静态工厂获取ActionContext的实例获取session,struts的特点返回是map，不是httpsession
			session.put("username", username);
			
			return SUCCESS;
		} else {
			request.setAttribute("url", "login.jsp");
			request.setAttribute("info", "失败");
			return ERROR;
		}
	}

}
